package com.ts.api.http.org.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.net.http.HttpRequestHeader;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.http.org.entity.apply.OrgApplyHeHuiHuaMask;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMaskConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMaskApply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMaskDataExchange;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 安心-合汇花MD5+8位
 * @ Author WJB
 * 对接文档：https://docs.qq.com/doc/DUEpmaEFESmZ1ck1E
 */
@ApiPlan(productId = "228", type = ApiPlanConvertType.ORG_PHONE_MASK)
public class ApiOrgPhoneMaskHeHuiHua implements ApiOrgPhoneMaskConvertHandler {

    private static final String KEY = "iYpxMAj3juDsvjKwwaYqBLDjM8KsYyYh";
    private static final String IV = "bec0fc9050c2ba82";
    private static final String CHANNEL_CODE = "20250604150850661021";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataChangeMessage) throws Exception {
        HttpRequestHeader httpRequestHeader = HttpRequestHeader.create("platformId", CHANNEL_CODE);
        apiDataChangeMessage.setHttpRequestHeader(httpRequestHeader);
        // 扩展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataChangeMessage);
        //  默认值
        String source = "3";
        Integer ProvidentFund = apiFieldConverter.hasProvidentFundToNumber();
        //  房产
        Integer house = apiFieldConverter.hasRealEstateInfoToNumber();
        //  车
        Integer car = apiFieldConverter.hasCarInfoToNumber();
        if (Eq.object(car, 1)){
            source = "1";
        }
        if (Eq.object(house, 1)){
            source = "2";
        }
        if (Eq.object(ProvidentFund, 1)){
            source = "4";
        }

        Map<Object, Object> newMap = new HashMap<>();
        newMap.put("city_name", apiDataChangeMessage.getCity());
        newMap.put("mobile", apiDataChangeMessage.getPhoneMask());
        newMap.put("source", source);

        //  加密方法
        return JsonUtils.toJson(newMap);
    }

    @Override
    public RespOrgPhoneMaskDataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespOrgPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("status"), 200)) {
            return RespOrgPhoneMaskDataExchange.ofFail();
        }
        JSONArray data = jsonObject.getJSONArray("data");
        if (ValidParam.isEmpty(data)) {
            return RespOrgPhoneMaskDataExchange.ofSuc();
        }
        RespOrgPhoneMaskDataExchange respOrgPhoneMaskDataExchange = RespOrgPhoneMaskDataExchange.ofSuc();
        List<String> md5 = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            // 获取数组中的每个元素
            String phoneMd5 = data.getString(i);
            md5.add(phoneMd5);
        }
        respOrgPhoneMaskDataExchange.setListPhoneMd5(md5);
        return respOrgPhoneMaskDataExchange;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyMessage) throws Exception {
        HttpRequestHeader httpRequestHeader = HttpRequestHeader.create();
        httpRequestHeader.add("platformId", CHANNEL_CODE);
        apiApplyMessage.setHttpRequestHeader(httpRequestHeader);

        OrgApplyHeHuiHuaMask data = new OrgApplyHeHuiHuaMask();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyMessage);
        data.setMobile(apiApplyMessage.getPhone());
        data.setCname(apiApplyMessage.getUserName());
        data.setCity(apiApplyMessage.getCity());
        //  贷款金额
        data.setMoney(apiFieldConverter.getLoanAmountUnit());
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别
        Integer sex = ChooseEq.create(apiApplyMessage.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        data.setSex(sex);
        data.setSource(3);
        //  车产
        Integer vehicle = ChooseEq.create()
                .when(apiApplyMessage.getCarInfo(), "1", 0)
                .when(apiApplyMessage.getCarInfo(), "2", 1)
                .when(apiApplyMessage.getCarInfo(), "3", 1)
                .when(apiApplyMessage.getCarInfo(), "4", 1)
                .end(0);
        data.setCar(vehicle);
        //  房产
        Integer house = ChooseEq.create()
                .when(apiApplyMessage.getRealEstateInfo(), "1", 0)
                .when(apiApplyMessage.getRealEstateInfo(), "2", 1)
                .when(apiApplyMessage.getRealEstateInfo(), "3", 1)
                .when(apiApplyMessage.getRealEstateInfo(), "4", 1)
                .when(apiApplyMessage.getRealEstateInfo(), "5", 1)
                .when(apiApplyMessage.getRealEstateInfo(), "6", 1)
                .end(0);
        data.setHouse(house);
        //  社保
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyMessage.getSocialSecurity(), "1", 0)
                .when(apiApplyMessage.getSocialSecurity(), "2", 1)
                .when(apiApplyMessage.getSocialSecurity(), "3", 1)
                .when(apiApplyMessage.getSocialSecurity(), "4", 1)
                .end(0);
        data.setShebao(socialSecurity);
        //  商业保险
        Integer commericalInsurance = ChooseEq.create()
                .when(apiApplyMessage.getInsurancePolicy(), "1", 0)
                .when(apiApplyMessage.getInsurancePolicy(), "2", 1)
                .when(apiApplyMessage.getInsurancePolicy(), "3", 1)
                .when(apiApplyMessage.getInsurancePolicy(), "4", 1)
                .end(0);
        data.setBaodan(commericalInsurance);
        //  信用卡
        Integer creditCard = ChooseEq.create(apiApplyMessage.getCreditLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .when("6", 1)
                .end(0);
        data.setCredit(creditCard);
        //  芝麻分
        String zhima = ChooseEq.create()
                .when(apiApplyMessage.getSesameCredit(), "1", "600分以下")
                .when(apiApplyMessage.getSesameCredit(), "2", "600~649分")
                .when(apiApplyMessage.getSesameCredit(), "3", "650~699分")
                .when(apiApplyMessage.getSesameCredit(), "4", "700分以上")
                .end("无");
        data.setZm_score(zhima);
        //  公积金
        Integer providentFund = ChooseEq.create()
                .when(apiApplyMessage.getProvidentFund(), "1", 0)
                .when(apiApplyMessage.getProvidentFund(), "2", 1)
                .when(apiApplyMessage.getProvidentFund(), "3", 1)
                .when(apiApplyMessage.getProvidentFund(), "4", 1)
                .end(0);
        data.setFunds(providentFund);
        //  工资发放
        String salaryMethod = ChooseEq.create(apiApplyMessage.getSalaryPayMethod())
                .when("1", "银行代发打卡")
                .when("2", "现金收入")
                .when("3", "个人转账")
                .end();
        data.setPayroll_type(salaryMethod);
        //  职业身份
        String professional = ChooseEq.create(apiApplyMessage.getCareer())
                .when("1", "上班族")
                .when("2", "自由职业")
                .when("3", "企业主（有营业执照）")
                .when("4", "公务员或事业单位")
                .when("5", "个体户")
                .end("上班族");
        data.setCompany_type(professional);
        //  营业执照
        Integer bizLicenseYear = ChooseEq.create()
                .when(apiApplyMessage.getBizLicenseYear(), "1", 0)
                .when(apiApplyMessage.getBizLicenseYear(), "2", 1)
                .when(apiApplyMessage.getBizLicenseYear(), "3", 1)
                .when(apiApplyMessage.getBizLicenseYear(), "4", 1)
                .end(0);
        data.setBusiness_license(bizLicenseYear);
        data.setItem_no(0);

        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String json = JsonUtils.toJson(data);
        String encrypt = aes.encryptToBase64Str(json);
        Map<Object, Object> dataMap = MapUtils.newHashMap(newMap -> {
            newMap.put("data", encrypt);
        });
        return JsonUtils.toJson(dataMap);
    }

    @Override
    public RespOrgPhoneMaskApply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespOrgPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("status"), 200)) {
            return RespOrgPhoneMaskApply.ofFail();
        }
        return RespOrgPhoneMaskApply.ofSuc();
    }
}
